using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.SocialPlatforms.Impl;
using UnityEngine.UI;

public class PlayerScript : MonoBehaviour {

    public float speed = 5.0f;
    public Rigidbody2D rb;
    public int Score = 0;
    public int ScoreMax = 0;
    public GameManger gm;
    public GameObject endGameUI;
    public GameObject ScoreUI;
    public GameObject NewScore;
    public Text ScoreNow;
    public Text ScoreBest;
    public GameObject[] Medal;
    private string path = "./Score.txt";
    public AudioSource sound;
    public AudioClip[] soundClips;

    // Start is called before the first frame update
    void Start() {
        Debug.Log("Start");
    }

    // Update is called once per frame
    void Update() {
        if (Input.GetMouseButtonDown(0)) {
            if (gm.PlayerDead == false) rb.velocity = new Vector2(0, speed);
            sound.PlayOneShot(soundClips[0]);
        }

        //Quaternion rotation = transform.rotation;
        //Quaternion targetrotation;

        if (rb.velocity.y > 0) {
            transform.rotation = Quaternion.Euler(0, 0, rb.velocity.y / speed * 30);
        }
        else if (rb.velocity.y < 0) {
            transform.rotation = Quaternion.Euler(0, 0, rb.velocity.y / speed * 30);
        }

        //transform.rotation = Quaternion.RotateTowards(rotation, targetrotation, 600 * Time.deltaTime);
        
        
        if (gm.GameStart) FlyBird();
    }

    private void OnCollisionEnter2D(Collision2D collision) {
        if (collision.gameObject.tag == "Obstacle" || collision.gameObject.tag == "Floor") {
            GameEnd();
        }
    }
     
    private void OnTriggerEnter2D(Collider2D collision) {
        if (collision.gameObject.tag == "ADDScore") {
            Score++;
            Debug.Log("Score:" + Score);
        }
    }

    private void GameEnd() {
        if (!gm.PlayerDead) sound.PlayOneShot(soundClips[1]);
        gm.PlayerDead = true;
        Invoke("StopGame", 1.5f);
        Debug.Log("Game Over");
    }

    protected void FlyBird() {
        rb.constraints = RigidbodyConstraints2D.None;
    }

    public void StopGame() {
        Time.timeScale = 0;
        endGameUI.SetActive(true);
        ScoreNow.text = Score.ToString();
        if (File.Exists(path)) {
            ScoreMax = int.Parse(File.ReadAllText(path));
        }
        if (Score > ScoreMax) {
            NewScore.SetActive(true);
            ScoreMax = Score;
            File.WriteAllText(path, ScoreMax.ToString());
        }
        ScoreBest.text = ScoreMax.ToString();
        if (Score >= 100) {
            Medal[0].SetActive(true);
        }
        else if (Score >= 10) {
            Medal[1].SetActive(true);
        }
        else {
            Medal[2].SetActive(true);
        }
        ScoreUI.SetActive(false);
        Debug.Log("Game Stop");
    }

}
 